package cn.agiledata.bank.transaction.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.dao.ActionTypeTemplate;
import cn.agiledata.bank.common.service.PermissionService;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.ForeDict;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.Operator;
import cn.agiledata.bank.transaction.dao.ReturnTransQueryPageList;
import cn.agiledata.bank.transaction.exception.TransactionException;
import cn.agiledata.bank.transaction.form.ReturnTransQueryForm;
import cn.agiledata.bank.transaction.logic.ReturnQueryBean;
import cn.agiledata.bank.transaction.service.TransactionService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class ReturnTransAction extends IPBBaseAction {
	
	private AccountTemplateInter getAccountTemplate() {
        return (AccountTemplateInter) IPBAppFactory
                .getObj(ForeDict.ACCOUNT_TEMPLATE);
    }
	
	/**
	 * 取得当前账户
	 * 
	 * @param request
	 * @return
	 */
    private Account getCurrentAccount(HttpServletRequest request) {
        long accountId = WeatherUtil.getAccountIdFromSession(request);
        return getAccountTemplate().getAccount(String.valueOf(accountId));
    }
    
    /**
     * 取得可以退款的交易类型列表actionType对象
     * 
     * @return
     */
    private List getReturnTypeList(List typeList) {
    	ActionTypeTemplate att = (ActionTypeTemplate) IPBAppFactory
				.getObj("actionTypeTemplate");
    	
    	Long [] arrIds = new Long[typeList.size()]; 
    	for (int i = 0; i < typeList.size(); i++) {
			arrIds[i] = (Long)typeList.get(i);
		}
    	return att.getActionTypeByIds(arrIds);
    }

	/**
	 * 退款交易查询
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
    public final ActionForward returnTransQuery(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
    	Account account = getCurrentAccount(request);
        request.setAttribute("subAccounts", account.getSubAccounts());
        
        ReturnTransQueryForm rtqForm = (ReturnTransQueryForm)form;
        PageBean pb = null;
        
        ReturnTransQueryPageList rtqPageList = null;
        
        if(rtqForm.getTransId() != null) {
        	// 执行查询
        	ReturnQueryBean queryBean = new ReturnQueryBean();
        	rtqPageList = new ReturnTransQueryPageList(queryBean);

        	queryBean.setAccount(getCurrentAccount(request));
        	String subAccountId = rtqForm.getSubAccountId();
            if (subAccountId != null && subAccountId.length() > 0) {
                queryBean.setSubAccountId(new Long(subAccountId));
            }

            String datertqFormat = "yyyy-MM-dd";
            String beginDate = rtqForm.getBeginDate();
            if (beginDate != null && beginDate.length() > 0) {
                queryBean.setBeginDate(DateUtil.string2Date(beginDate, datertqFormat));
            }
            String endDate = rtqForm.getEndDate();
            if (endDate != null && endDate.length() > 0) {
                queryBean.setEndDate(DateUtil.string2Date(endDate, datertqFormat));
            }
            queryBean.setTransId(rtqForm.getTransId());
            queryBean.setOrderId(rtqForm.getOrderId());
            String minAmount = rtqForm.getMinAmount();
            if (minAmount != null && minAmount.length() > 0) {
                queryBean.setMinAmount(new Double(minAmount));
            }
            String maxAmount = rtqForm.getMaxAmount();
            if (maxAmount != null && maxAmount.length() > 0) {
                queryBean.setMaxAmount(new Double(maxAmount));
            }
            String strActionType = rtqForm.getActionType();
            if(strActionType != null && strActionType.length() > 0) {
            	queryBean.setActionType(new Long(strActionType));
            }
            queryBean.setStartPage(rtqForm.getStartPage());
        	pb = rtqPageList.getAccountListPageBean();
        }
        else {
	        pb = new PageBean();
	        pb.setData(new ArrayList());
	        rtqPageList = new ReturnTransQueryPageList(null);
        }
        
        // 交易类型
        request.setAttribute("typeList", getReturnTypeList(rtqPageList
				.getReturnActionType()));
        request.setAttribute("result", pb);

        return mapping.findForward("list");
    }
    
    /**
     * 申请退款交易列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public final ActionForward returnApplyList(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
    	// 取得当前登录账户
    	Account account = getCurrentAccount(request);
    	
    	// 选中的ID
    	String[] arrSelectIds = request.getParameterValues("checkId");
    	// 翻页数
    	String strStartPage = request.getParameter("startPage");
    	
    	Long[] arrIds = null;
    	if(arrSelectIds != null && arrSelectIds.length > 0) {
    		arrIds = new Long[arrSelectIds.length];
    		for (int i = 0; i < arrSelectIds.length; i++) {
				arrIds[i] = new Long(arrSelectIds[i]); 
			}
    	}
    	
    	ReturnQueryBean pageBean = new ReturnQueryBean();
    	pageBean.setStartPage(strStartPage);
    	pageBean.setAccount(account);
    	
    	// 查询选中的交易
    	ReturnTransQueryPageList rtqPage = new ReturnTransQueryPageList(arrIds,pageBean);
    	
    	PageBean pb = rtqPage.getAccountListPageBean();
    	request.setAttribute("result", pb);
    	
    	return mapping.findForward("list");
    }
    
    /**
     * 生成退款申请
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public final ActionForward returnApply(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
    	// 取得当前登录账户
    	Account account = getCurrentAccount(request);
    	
    	// 判断当前用户是否具有付款权限
        PermissionService permissionService = PermissionService
                .getPermissionService();
        if (!permissionService.hasPermission(request,
                Constant.PERMIS_TYPE_PAYMONEY)) {
            handleAppException(mapping, form, request, response,
                    TransactionException.NO_PERMISSION);
        }
    	
    	// 退款交易ID
    	String[] arrReturnIds = request.getParameterValues("id");
    	
    	// 退款金额
    	String[] arrReturnAmounts = request.getParameterValues("returnAmount");
    	
    	// 数据异常，返回
    	if (arrReturnIds == null || arrReturnIds.length == 0
				|| arrReturnAmounts == null || arrReturnAmounts.length == 0) {
    		throw TransactionException.TRANSACTION_FAILED;
		}
    	
    	Long[] arrIds = null;
    	if(arrReturnIds != null && arrReturnIds.length > 0) {
    		arrIds = new Long[arrReturnIds.length];
    		for (int i = 0; i < arrReturnIds.length; i++) {
				arrIds[i] = new Long(arrReturnIds[i]); 
			}
    	}
    	
    	Map mapAmounts = null;
    	if(arrReturnAmounts != null && arrReturnAmounts.length > 0) {
    		mapAmounts = new HashMap();
    		for (int i = 0; i < arrReturnAmounts.length; i++) {
    			mapAmounts.put(arrIds[i], validateAmount(arrReturnAmounts[i]));
    			
			}
    	}

    	// 取得操作员
    	AccountSummary accountsummary = WeatherUtil
				.getLoingInfoFromSession(request);
		String operatorId = accountsummary.getOperatorCode() == null ? null
				: accountsummary.getOperatorCode().toString();
		Operator operator = operatorId == null ? null : accountsummary
				.getOperatorByIdInstance(operatorId);
    	
    	TransactionService transService = (TransactionService) IPBAppFactory
				.getObj(ForeDict.SERVICE_TRANSACTION);
    	transService.createReturnApply(arrIds, mapAmounts, account, operator);
    	
    	// 操作成功
    	request.setAttribute("back",request.getContextPath()+mapping.findForwardConfig("back").getPath());
    	return mapping.findForward(FORWARD_GLOBAL_SUCCESS);
    }
    
    /**
     * 检查金额
     * 
     * @param amountValue
     * @return
     * @throws TransactionException
     */
    private Double validateAmount(String amountValue)
			throws TransactionException {
		try {
			Double amount = new Double(amountValue);
			if (amount.doubleValue() <= 0) {
				throw TransactionException.INVALID_AMOUT;
			}
			return amount;
		} catch (NumberFormatException e) {
			throw TransactionException.INVALID_AMOUT;
		}
	}
}
